import { Table } from '@tiptap/extension-table'
import { Plugin, PluginKey } from 'prosemirror-state'

export default Table.extend({
  name: 'customTable',

  addProseMirrorPlugins() {
    const parent = this.parent?.() || []

    return [
      ...parent,
      new Plugin({
        key: new PluginKey('customTableSelection'),
        view: () => ({
          update: (view, prevState) => {
            const { state } = view
            const { selection } = state
            const { node } = selection

            // 获取组件实例
            const component = this.editor.storage.component
            if (!component) return

            // 检查是否选中了表格节点
            const isTableSelected = !selection.empty && !!node && node.type.name === 'customTable'

            if (isTableSelected !== component.isTableSelected) {
              // 更新选中状态
              setTimeout(() => {
                component.updateTableState()
                component.updateFloatingToolbar()
              }, 10)
            }
          }
        })
      })
    ]
  },

  addKeyboardShortcuts() {
    return {
      // 添加删除表格的快捷键
      'Mod-Shift-Backspace': () => {
        const { state } = this.editor
        const { selection } = state
        const { node } = selection

        // 如果选中了整个表格，删除它
        if (!selection.empty && node && node.type.name === 'customTable') {
          return this.editor.chain().focus().deleteTable().run()
        }
        return false
      }
    }
  }
})
